package com.wnxy.article.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wnxy.article.entity.Article;
import com.wnxy.article.service.ArticleService;
import com.wnxy.common.base.PageBean;
import com.wnxy.common.base.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/article")
@Api(tags = "文章管理")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    /**
     * 1、文章列表分页
     * 问题：支持不同组件统一分页返回，所以这里不能直接返回MyBatis-Plus提供的Page对象；太多冗余
     * 解决：自定义分页Bean
     */
    @GetMapping
    @ApiOperation("文章列表分页")
    public Result<PageBean<Article>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "5") Integer size){
        Page<Article> page = articleService.page(new Page<>(current, size));
        PageBean<Article> pageBean = PageBean.fill(page);
        // 统一返回结果
        return Result.ok(pageBean);
    }

    /**
     * 2、查看详情
     */
    @GetMapping("{id}")
    @ApiOperation("查看详情")
    public Result<Article> findInfosById(
            @ApiParam(name = "id",value = "文章id",required = true)
            @PathVariable("id") Integer id) {
        // 参数判断
        Assert.notNull(id,"ID不能为空！");
        // 根据id查询
        Article article = articleService.getById(id);
        // 判断
        Assert.notNull(article,"ID不存在!");
        // 更新查看次数 update informations set view_count=view_count+1 where id=?
        LambdaUpdateWrapper<Article> wrapper = Wrappers.lambdaUpdate(Article.class)
                .set(Article::getViewCount, article.getViewCount() + 1)
                .eq(Article::getId, article.getId());
        articleService.update(wrapper);
        return Result.ok(article);
    }

    /**
     * 3、修改回复数量; 给回复系统远程调用
     */
    @PutMapping("{id}")
    public Result updateInfosReplyCount(@PathVariable Integer id){
        // 通过sql片段更新
        Wrapper<Article> wrapper = Wrappers.lambdaUpdate(Article.class)
                .setSql("reply_count=reply_count+1")
                .eq(Article::getId, id);
        articleService.update(wrapper);
        return Result.ok();
    }
}
